var service = new EbeimService();
var $pagesize = 10;
var $pageNo = 1;
var isSelf="1";
var $dsName='';
var dsCB = function(data){
	var content = "";
	for(var i=0;i<data.list.length;i++){
		var obj = data.list[i];
		var dsStatus = obj.dsStatus;
		var statusBtn = "<font color='red'>禁用</font>";
		if(dsStatus == "1"){
			dsStatus = 0;
			statusBtn = "<font color='green'>启用</font>"; 
		}else{
			dsStatus = 1;
		}
		var backupBtnFunc = "handBackup(\"" + obj.id + "\","+ obj.dsSecurityRank + ")";
		if(data.terminalId != obj.terminalId){
			backupBtnFunc = "plugin.msgtip({type: \"e\", msg: \"非本设备文件夹，无法操作!\"});";
		}
		content = content
		+"<tr>"
		+"	<td><input dsrank='"+ obj.dsSecurityRank + "' type='checkbox' name='ck' value="+obj.id+"></td>"
		+"	<td>"+(i+1)+"</td>"
		+"	<td><input class='inp-name' type='text' value='"+obj.name+"' readonly='readonly' style='width:134px'></td>"
		+"	<td>"+obj.bindDeviceName+"</td>"
		+"	<td>"+getTimeStr(obj.createTime)+"</td>"
		+"	<td>"+translateStatus(obj.dsStatus,obj.status,obj.id)+"</td>"
		+"	<td class='' dsStatus='"+obj.dsStatus+"'>"
		+"		<button class='opr-btn' type='button' id='statusBtn"+obj.id+"' onclick='javascript:changeDsStatus("+dsStatus+",\"" + obj.id + "\","+ obj.dsSecurityRank + ")'>"+statusBtn+"</button>"
		+"		<button class='opr-btn' type='button' onclick='toPage(\"/web/html/web_data_form.html?dsType="+$("#h_dsType").val()+"&dsId="+obj.id+"\")'>编辑</button>"
		+"		<button class='opr-btn' type='button' id='backupBtn"+obj.id+"' onclick='javascript:"+backupBtnFunc+"'>备份</button>"
		+"		<button class='opr-btn' type='button' onclick='goToclientFolder(obj.currentVersionMajor+\".0\");toPage(\"/web/html/clientFolder.html?dsType="+$("#h_dsType").val()+"&dsId="+obj.id+"&terminalId="+obj.terminalId+"&version="+obj.currentVersionMajor+".0"+"&path="+"/"+"\")'>列表</button>"
		+"	</td>"
		+"</tr>";
	}
	if(data.list.length>0){
		$("#tbody").html(content);
	}else{
		$("#tbody").html("<tr><td colspan='7' style='text-align:center;'>暂无数据</td></tr>");
	}
	gennerPage(data.page.totalPage,data.page.totalRecord);
	getUploadProcessBar();
}
function setDynamicCode() {
	var dynamicCode = $("#dynamicCode").val();
	if (dynamicCode == "") {
		plugin.msgtip({type: "e", msg: "动态验证码不能为空!"});
		return;
	}
	var dsId = $("#h_dsId").val();
	var dsSecurityRank = $("#h_dsSecurityRank").val();
	var whichGetModel = $("#h_whichGetModel").val();
	if (whichGetModel == "handBackup") {
		handBackup(dsId, dsSecurityRank, dynamicCode)
	} else if (whichGetModel == "changeDsStatus") {
		var dsStatus = $("#h_dsStatus").val();
		changeDsStatus(dsStatus, dsId, dsSecurityRank, dynamicCode)
	} else if (whichGetModel == "changeDsStatusMany") {
		var dsStatus = $("#h_dsStatus").val();
		changeDsStatusMany(dsStatus,dynamicCode);
	}
}
var handBackupCB = function(data) {
	var dsid = $("#h_dsId").val();
	$("#backupBtn"+dsid).removeAttr("disabled");
	var json = data;
	if (json.code == "200" || json.code == 200) {
		plugin.msgtip({type: "o", msg: "成功加入备份队列!"});
		closeCodeWindow();
		$("#dynamicCode").val("");
	} else {
		dsSecurityRankCheck(json,json.message);
	}

}
function handBackup(dsId, dsSecurityRank, dynamicCode) {
	var currentDsStatus = $("#statusBtn"+dsId).parent().attr("dsStatus");
	if(currentDsStatus=="1"){
		plugin.msgtip({type:"e",msg:"该数据源已被禁用!"});
		return;
	}
	$("#h_whichGetModel").val("handBackup");
	$("#h_dsId").val(dsId);
	$("#h_dsSecurityRank").val(dsSecurityRank);
	$("#backupBtn"+dsId).attr("disabled","disabled");
	service.backup(
			{
				dsId:dsId,
				dsSecurityRank:dsSecurityRank,
				dynamicCode:dynamicCode
			},
			handBackupCB
	);
}
//数据源列表
function getDateSoucesByPage(){
//	var pageNo = getParameter('pno');
//	if(pageNo==undefined||pageNo==""){
//		pageNo = 0;
//	}
	service.getDataSourcesByPage({
		offset:$pageNo,
		pagesize:$pagesize,
		dsType:$("#h_dsType").val(),
		dsStatus:"",
		name:$dsName,
		isSelf:isSelf
	}, dsCB);
}

//启用禁用
function changeDsStatusMany(flag,dynamicCode){
	var ids = getCkValue("ck");
	var dsSecurityRank = 0;
	$("input[name='ck']:checked").each(function(){
		var v = $(this).attr("dsrank");
		if(v=="1" && dsSecurityRank !=2){
			dsSecurityRank  = 2;
		}
		if(v=="2"){
			dsSecurityRank  = 2;
		}
	});
	if(ids.length==0){
		plugin.msgtip({type:"e",msg:"请至少选择一项进行操作!"});
		return;
	}
	$("#h_dsStatus").val(flag);
	$("#h_whichGetModel").val("changeDsStatusMany");
	service.updataStatusMany({
		ids:ids,
		dsStatus:flag,
		dsSecurityRank:dsSecurityRank,
		dynamicCode:dynamicCode,
	},
	function(data){
		if(data.code=="200"){
			$("#ckall")[0].checked = false;
			closeCodeWindow();
			getDateSoucesByPage();
		}else if(data.code=="500"){
			plugin.msgtip({type:"e",msg:data.message});
			return;
		}else{
			closeCodeWindow();
			dsSecurityRankCheck(data);
		}
	});
}
function changeDsStatus(dsStatus, dsId, dsSecurityRank, dynamicCode) {
	$("#h_dsId").val(dsId);
	$("#h_dsSecurityRank").val(dsSecurityRank);
	$("#h_dsStatus").val(dsStatus);
	$("#h_whichGetModel").val("changeDsStatus");
	var ds = {
		id : dsId,
		dsStatus : dsStatus,
		dsSecurityRank : dsSecurityRank,
		dynamicCode : dynamicCode
	};
	$("#statusBtn"+dsId).attr("disabled","disabled");
	$dsId = dsId;
	var json = {};
	json["datasource"] = ds;
	service.addDataSource(json, changStatusCB);
}
var changStatusCB = function(data) {
	$("#statusBtn"+$dsId).removeAttr("disabled");
	var json = data;
	if (json.code == "200") {
		plugin.msgtip({type: "o", msg: "操作成功"});
		closeCodeWindow();
		$("#dynamicCode").val("");
		getDateSoucesByPage();
	} else {
		dsSecurityRankCheck(json,json.message);
	}
}

function translateStatus(dsStatus,status, dsId) {
	var color = "green";
	if(dsStatus==1){
		status = "禁用";
		color = "red";
	}
	else if (status == 0) {
		status = "等待备份";
	} else if (status == 1) {
		status = "备份中";
	} else if (status == 2) {
		status = "备份失败";
		color = "red";
	} else if (status == 3) {
		status = "备份成功，等待下次备份";
	}
	var str = "<div class='processbar' dsid='"
		+ dsId
		+ "' style='background:#ddd;width:150px;height:20px;position:relative;margin:0 auto;'>"
		+ "<div class='bar' style='height:20px;'></div>"
		+ "<div class='info' style='font-size:12px;width:150px;height:20px;color:"+color+";position:absolute;top:0;left:0'>"+status+"</div>"
		+ "</div>";
	return str;
}

function otherTerminlalCheck(){
	if($("#otherTerminal")[0].checked){
		isSelf="0";
	}else{
		isSelf="1";
	}
}

//init
$(function(){
	var dsType = getParameter("dsType");
	$dsName = getParameter("dsName");
	$("#h_dsType").val(dsType);
	if(dsType != "0" && dsType != "1" && dsType != "2"){
		plugin.msgtip({type: "o", msg: "参数缺失！"});
		window.history.go(-1);
	}
	getDateSoucesByPage();
	setInterval("getUploadProcessBar()", 2500);
	
	$("#otherTerminal").change(function(){
		otherTerminlalCheck();
		getDateSoucesByPage();
	});
});


var uploadPrcessBarCB = function(data) {
	var list = data.beans;
	for (var i = 0; i < list.length; i++) {
		var bean = list[i];
		var fileSum = bean.fileSum;
		var okSum = bean.okSum;
		var errorSum = bean.errorSum;
		$(".processbar").each(
			function() {
				var dsid = $(this).attr("dsid");
				if (dsid == bean.dsId) {
					$(this).css("border", "solid 1px green");
					$(this).find(".bar").css("background", "green");
					$(this).find(".info").css("color", "#fff")
					if (bean.count >= bean.total || okSum+errorSum>=fileSum) {
						$(this).find(".bar").css("width", 100 + "%");
						$(this).find(".info").html("100.00%");
						$(this).css("border", "0");
						$(this).find(".bar").css("width", 0);
						$(this).find(".info").css("color", "green")
						$(this).find(".info").html("文件校验中...");
					} else {
						var p = (bean.count * 100 / bean.total).toFixed(2);
						$(this).find(".bar").css("width",p+ "%");
						if(p == 0 && errorSum==0){
							$(this).find(".info").html("正在加密中...");
						}else if(p == 0 && errorSum==fileSum){
							$(this).find(".info").html("上传失败!");
						}else{
							$(this).find(".info").html(
									(bean.count * 100 / bean.total).toFixed(2)
											+ "%");
						}
					}

				}
			});
	}
}
function getUploadProcessBar() {
	var ids = "";
	$(".processbar").each(function() {
		ids += $(this).attr("dsid") + ",";
	});
	if (ids.length > 0) {
		ids = ids.substring(0, ids.length - 1);
		
		service.getUploadProcessBar(
			{
				dsIds:ids
			}, 
			uploadPrcessBarCB
		);
		
		service.deleteUploadProcessBar(
			{
				dsIds:ids
			},
			delProcessbarCB,
			function(data){
				window.location.href = "/web/html/login.html";
			}
		);
	}
}

var delProcessbarCB = function(data) {
	if(data.code=="200"){
		window.location.reload();
	}
}

//分页控件
function gennerPage(totalPage,totalRecords){
	if(totalPage==0){
		totalPage = 1;
	}
    //分页参数，有些参数是可选的，比如lang，若不传有默认值
    var pageData = {
        pno : $pageNo,
        //总页码
        total : totalPage,
        //总数据条数
        totalRecords : totalRecords,
	    mode : 'click',//默认值是link，可选link或者click
	    click : function(n){
	    	$pageNo = n;
	    	otherTerminlalCheck();
    		service.getDataSourcesByPage({
				offset:n,
				pagesize:$pagesize,
				dsType:$("#h_dsType").val(),
				dsStatus:"",
				name:$dsName,
				isSelf:isSelf
			}, dsCB);
	    }
    	}
    //初始化分页
    kkpager.init(pageData);
    //生成分页
    //有些参数是可选的，比如lang，若不传有默认值
    kkpager.generPageHtml(pageData);
}
//全选
function checkAll(spId,ckName){
	if($("#"+spId)[0].checked){
		$("input[name='"+ckName+"']").each(function(){
			$(this)[0].checked = true;
		});
	}else{
		$("input[name='"+ckName+"']").each(function(){
			$(this)[0].checked = false;
		});
	}
}
//获取选择的值
function getCkValue(ckName){
	var rs = "";
	$("input[name='"+ckName+"']").each(function(){
		if($(this)[0].checked){
			rs = rs + $(this).attr("value") + ","
		}
	});
	if(rs.length > 0){
		rs = rs.substring(0,rs.length-1);
	}
	return rs;
}
//
function goToclientFolder(version){
	if (version == "") {
		plugin.msgtip({type: "e", msg: "您当前没有版本可以下载!"});
		return;
	}
}
